# -*- coding: utf-8 -*-

from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse

import datetime
import logging

from usuarios.forms import LoginForm
from usuarios.decorators import login_required, superuser_required

def login(request):
    redirect_to = request.REQUEST.get('next', '').strip()
    if not redirect_to:
        redirect_to = reverse('index')
    if 'auth' in request.session:
        if request.is_ajax():
            return HttpResponse(u'Você já está logado.')
        else:
            return HttpResponseRedirect(redirect_to)
    form = LoginForm()
    if request.method == 'POST':
        form = LoginForm(request.POST)
        logger = logging.getLogger('usuarios.views.login')
        if form.is_valid():
            user = form.get_user()
            user.ultimo_acesso = datetime.datetime.now()
            user.save()
            request.session['auth'] = user.id
            logger.info('LOGIN SUCCESS %s [id: %d]', user.usuario, user.id)
            if request.is_ajax():
                return HttpResponse(u'Login realizado com sucesso.')
            else:
                return HttpResponseRedirect(redirect_to)
        logger.warn('LOGIN FAILED \'%s\'', form.data.get('usuario', None))
    context = {
        'form': form,
        'next': redirect_to,
    }
    if request.is_ajax():
        return HttpResponse(u'Usuário e senha inválidos.', status=401)
    else:
        return render_to_response('usuarios/login.html', context, context_instance=RequestContext(request))


def logout(request):
    if 'auth' in request.session:
        user = request.user
        del request.session['auth']
        logger = logging.getLogger('usuarios.views.logout')
        logger.info('LOGOUT %s [id: %d]', user.usuario, user.id)
    if request.is_ajax():
        return HttpResponse(u'Logout realizado com sucesso.')
    else:
        return HttpResponseRedirect(reverse("index"))


@login_required
def auth_direct_to_template(*args, **kwargs):
    from django.views.generic.simple import direct_to_template
    return direct_to_template(*args, **kwargs)


@login_required
def auth_gridcrud_run(*args, **kwargs):
    from vialink.django.gridcrud import run
    return run(*args, **kwargs)


